【Codewars每日一题】- Find The Parity Outlier

题目

题目地址

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this “outlier” N.

Examples

1
2
3
4
5
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11 (the only odd number)

[160, 3, 1719, 19, 11, 13, -21]
Should return: 160 (the only even number)

思路

最直接的思路就是遍历数组,前提要判断我们要找的目标是一个奇数还是偶数。根据数组中的前三个数字可以判断出目标数是奇还是偶。然后遍历数组,找到目标数。

答案

我的答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def find_outlier(integers):
if (isOddList(integers)):
for i in integers:
if not isOdd(i):
return i
else:
for i in integers:
if isOdd(i):
return i

# 判断是否是奇数
def isOdd(num):
if (num % 2) == 0:
return False
else:
return True


# 判读是否是奇数数组,以前三个元素判断即可
def isOddList(integers):
odd = 0
even = 0
for i in integers[0:3]:
if (i % 2) == 0:
even += 1
else:
odd += 1
if odd > even:
return True
else:
return False

最佳答案

1
2
3
4
def find_outlier(int):
odds = [x for x in int if x%2!=0]
evens= [x for x in int if x%2==0]
return odds[0] if len(odds)<len(evens) else evens[0]

最佳答案的思路是分别将奇数和偶数筛选出为单独的list,然后比较最终的list大小可以得出目标数。该方法看着简洁明了。

hoxis wechat
一个脱离了高级趣味的程序员,关注回复1024有惊喜~
赞赏一杯咖啡
0%